{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "_dEaVsqSgNyQ"
      },
      "source": [
        "##### Copyright 2021 The TensorFlow Authors."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "4FyfuZX-gTKS"
      },
      "outputs": [],
      "source": [
        "#@title Licensed under the Apache License, Version 2.0 (the \"License\");\n",
        "# you may not use this file except in compliance with the License.\n",
        "# You may obtain a copy of the License at\n",
        "#\n",
        "# https://www.apache.org/licenses/LICENSE-2.0\n",
        "#\n",
        "# Unless required by applicable law or agreed to in writing, software\n",
        "# distributed under the License is distributed on an \"AS IS\" BASIS,\n",
        "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n",
        "# See the License for the specific language governing permissions and\n",
        "# limitations under the License."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "sT8AyHRMNh41"
      },
      "source": [
        "# TensorFlow Ranking Landing Page Example\n",
        "\n",
        "\u003ctable class=\"tfo-notebook-buttons\" align=\"left\"\u003e\n",
        "  \u003ctd\u003e\n",
        "    \u003ca target=\"_blank\" href=\"https://www.tensorflow.org/ranking/overview\"\u003e\u003cimg src=\"https://www.tensorflow.org/images/tf_logo_32px.png\" /\u003eView on TensorFlow.org\u003c/a\u003e\n",
        "  \u003c/td\u003e\n",
        "  \u003ctd\u003e\n",
        "    \u003ca target=\"_blank\" href=\"https://github.com/tensorflow/ranking/blob/master/examples/keras/landingpage_example.ipynb\"\u003e\u003cimg src=\"https://www.tensorflow.org/images/GitHub-Mark-32px.png\" /\u003eView source on GitHub\u003c/a\u003e\n",
        "  \u003c/td\u003e\n",
        "\u003c/table\u003e"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "8f-reQ11gbLB"
      },
      "source": [
        "In this landing page example, we build a single tower ranking model using the [MSLR-Web10K dataset](https://www.microsoft.com/en-us/research/project/mslr/) with TF-Ranking."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "6yzAaM85Z12D"
      },
      "outputs": [],
      "source": [
        "# Install TF-Ranking and TF Dataset.\n",
        "!pip install -q tensorflow-ranking\n",
        "!pip install -q --upgrade tfds-nightly"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "n3oYt3R6Nr9l"
      },
      "outputs": [],
      "source": [
        "import tensorflow as tf\n",
        "import tensorflow_datasets as tfds\n",
        "import tensorflow_ranking as tfr\n",
        "\n",
        "# Load MSLR-WEB10K dataset from TFDS.\n",
        "ds = tfds.load(\"mslr_web/10k_fold1\", split=\"train\")\n",
        "\n",
        "# Add a mask tensor.\n",
        "ds = ds.map(lambda feature_map: {\n",
        "    \"_mask\": tf.ones_like(feature_map[\"label\"], dtype=tf.bool),\n",
        "    **feature_map\n",
        "})\n",
        "\n",
        "# Shuffle data and create padded batches for queries with different lengths.\n",
        "# Padded items will have False on `_mask`.\n",
        "ds = ds.shuffle(buffer_size=1000).padded_batch(batch_size=32)\n",
        "\n",
        "# Create (features, labels) tuples from data and set -1 label for masked items.\n",
        "ds = ds.map(lambda feature_map: (\n",
        "    feature_map, tf.where(feature_map[\"_mask\"], feature_map.pop(\"label\"), -1.)))\n",
        "\n",
        "# Create a model with Keras Functional API.\n",
        "inputs = {\n",
        "    name: tf.keras.Input(shape=(None, 1), dtype=tf.float32, name=name)\n",
        "    for name in ds.element_spec[0]\n",
        "    if name != \"_mask\"\n",
        "}\n",
        "norm_inputs = [tf.keras.layers.BatchNormalization()(x) for x in inputs.values()]\n",
        "x = tf.concat(norm_inputs, axis=-1)\n",
        "for layer_width in [128, 64, 32]:\n",
        "  x = tf.keras.layers.Dense(units=layer_width)(x)\n",
        "  x = tf.keras.layers.Activation(activation=tf.nn.relu)(x)\n",
        "scores = tf.squeeze(tf.keras.layers.Dense(units=1)(x), axis=-1)\n",
        "\n",
        "# Create, compile and train the model.\n",
        "model = tf.keras.Model(inputs=inputs, outputs=scores)\n",
        "model.compile(\n",
        "    optimizer=tf.keras.optimizers.Adam(learning_rate=0.01),\n",
        "    loss=tfr.keras.losses.SoftmaxLoss(),\n",
        "    metrics=tfr.keras.metrics.get(\"ndcg\", topn=5, name=\"NDCG@5\"))\n",
        "model.fit(ds, epochs=3)"
      ]
    }
  ],
  "metadata": {
    "colab": {
      "collapsed_sections": [],
      "name": "landingpage_example.ipynb",
      "private_outputs": true,
      "provenance": [],
      "toc_visible": true
    },
    "kernelspec": {
      "display_name": "Python 3",
      "language": "python",
      "name": "python3"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 0
}
